package com.uenpay.im.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.adapter.QiYunXinAdapter;
import com.qiyunxin.android.http.listener.OnMediaPlayerListener;
import com.qiyunxin.android.http.media.Player;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.message.type.SendMsgCallBackResult;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.QyxMsgView;
import com.qyx.android.utilities.DateUtils;
import com.qyx.android.weight.edittext.Emoji;
import com.qyx.android.weight.utils.QyxWeightDensityUtils;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.LinkDefs;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.chat.MsgOtherType;
import com.uenpay.im.ui.old.activity.chat.SendMsgHandle;
import com.uenpay.im.ui.old.activity.chat.manage.ChatItemDataManager;
import com.uenpay.im.ui.old.activity.chat.manage.ChatItemViewHolder;
import com.uenpay.im.ui.old.activity.chat.manage.ChatItemViewManager;
import com.uenpay.im.ui.old.activity.chat.manage.ChatMsgManage;
import com.uenpay.im.ui.old.activity.chat.manage.ChatTypeManage;
import com.uenpay.im.ui.old.activity.contacts.ContactsHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.OnCommonCallBack;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.SendFile;
import com.uenpay.im.entities.chatbean.AttachModel;
import com.uenpay.im.entities.chatbean.MsgAudioModel;
import com.uenpay.im.entities.chatbean.MsgGifModel;
import com.uenpay.im.entities.chatbean.MsgRequestVideoChatModel;
import com.uenpay.im.invokeitems.HttpRequestHandle;
import com.uenpay.im.invokeitems.chat.RevokeMsgInvokeItem;
import com.uenpay.im.invokeitems.contacts.ApplyAddFriendInvokItem;
import com.uenpay.im.utilities.QyxDateUtils;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.ZProgressHUD;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 会话列表adapter
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */

public class ChatAdapter extends QiYunXinAdapter {
    /**
     * 文件工具类实例
     */
    private FileUtils fileUtils = new FileUtils(IMApplication.appName);
    private ChatMsgManage mChatMsgManage = null;
    private ChatItemViewHolder mChatItemViewHolder = null;
    /**
     * 消息集合
     **/
    public ArrayList<QyxMsgView> _msgList;
    /**
     * 时间消息集合
     **/
    public int time_msg_count = 0;
    /**
     * 未读消息分割线
     **/
    public int unread_msg_line = 0;
    private Context mContext;
    boolean bl = true;
    /**
     * 本地消息数据库操作类
     **/
    private TalkMsgManager takeMsgManager = new TalkMsgManager();
    // private TopListMsgManager topListMsgManager = new TopListMsgManager();
    // private ListView mListView;
    private int sound_msg_bg_total_width;
    private EditText mEditText;
    private Emoji mEmoji;
    private SendFile mSendFile = null;
    private int is_show_group_member_name = 0;
    /**
     * 待播放语音列表
     */
    private ArrayList<QyxMsgView> playMediaList = new ArrayList<QyxMsgView>();

    /**
     * @param context
     * @param msgList
     * @param mEditText
     * @param _is_show_group_member_name
     */
    public ChatAdapter(Context context, ArrayList<QyxMsgView> msgList,
                       EditText mEditText, int _is_show_group_member_name) {
        unread_msg_line = 0;
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        is_show_group_member_name = _is_show_group_member_name;
        mSendFile = new SendFile();
        this.mEditText = mEditText;
        this.mContext = context;
        _msgList = msgList;
        mChatMsgManage = new ChatMsgManage(context);
        mChatItemViewHolder = new ChatItemViewHolder();
        Player.getInstance().SetOnMediaPlayerListener(
                new OnMediaPlayerListener() {

                    @Override
                    public void onSeekComplete(int currentMills,
                                               int totalMills, int videoWidth, int videoHeight) {
                    }

                    @Override
                    public void onPlayComplete() {
                        if (last_palying_index != null) {
                            last_palying_index.is_playing = false;
                            notifyDataSetChanged();
                        }
                        playMediaByTempList();
                    }

                    @Override
                    public void onFail(String reason) {
                        if (last_palying_index != null) {
                            last_palying_index.is_playing = false;
                            notifyDataSetChanged();
                        }
                        playMediaByTempList();
                    }
                });

        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        sound_msg_bg_total_width = dm.widthPixels
                - QyxWeightDensityUtils.dp2px(context, 120);
        mEmoji = new Emoji();
    }

    /**
     * 设置是否显示群成员昵称
     *
     * @param is_show 1:显示
     */
    public void setIsShowMemberName(int is_show) {
        this.is_show_group_member_name = is_show;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return _msgList.size();
    }

    @Override
    public QyxMsgView getItem(int position) {
        return _msgList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        /** 对应值为ChatTypeManage中的类型个数 **/
        return 42;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final QyxMsgView mQyxMsgView = getItem(position);
        mQyxMsgView.index = position;
        final QyxMsg message = mQyxMsgView.msg;
        /** 头像地址 **/
        String avatar_path = APIConfiguration.getAvatarUrlNormal(
                message.from_cust_id + "", PacketType.PERSONAL);
        ChatItemViewHolder.BaseViewHolder baseHolder = mChatItemViewHolder.new BaseViewHolder();
        ChatItemViewHolder.TimeViewHolder timeHolder = mChatItemViewHolder.new TimeViewHolder();
        /** 新闻消息 **/
        ChatItemViewHolder.NewsViewHolder newsViewHolder = null;
        ChatItemViewHolder.SystemViewHolder systemHolder = null;
        ChatItemViewHolder.RedSystemViewHolder redSystemViewHolder = null;
        ChatItemViewHolder.UnreadMsgViewHolder unreadMsgViewHolder = null;
        ChatItemViewHolder.VerifMsgViewHolder verifMsgViewHolder = null;
        ChatItemViewHolder.ReceivedTextViewHolder receivedTextHolder = null;
        ChatItemViewHolder.ReceivedImageViewHolder receivedImageHolder = null;
        ChatItemViewHolder.ReceivedAudioViewHolder receivedAudioHolder = null;
        ChatItemViewHolder.ReceivedLocationViewHolder receivedLocationHolder = null;
        ChatItemViewHolder.ReceivedGifViewHolder receivedGifHolder = null;
        ChatItemViewHolder.ReceivedFileViewHolder receivedFileHolder = null;
        ChatItemViewHolder.ReceivedCradViewHolder receivedCradViewHolder = null;
        ChatItemViewHolder.ReceivedRedViewHolder receivedRedViewHolder = null;
        ChatItemViewHolder.ReceivedVideoChatViewHolder receivedVideoChatViewHolder = null;
        ChatItemViewHolder.ReceivedOANoticeViewHolder receivedOANoticeViewHolder = null;
        ChatItemViewHolder.ReceivedOAViewHolder receivedOAViewHolder = null;
        ChatItemViewHolder.ReceivedOATaskViewHolder receivedOATaskViewHolder = null;
        ChatItemViewHolder.ReceivedTransferViewHodler receivedTransferViewHodler = null;
        ChatItemViewHolder.ReceivedCrownFundViewHodler receivedCrownFundViewHodler = null;
        /** 众筹系统消息 **/
        ChatItemViewHolder.ReceivedCrowdFundSystemViewHodler crowdFundSystemViewHodler = null;
        ChatItemViewHolder.ReceivedInvitJoinGroupViewHodler receivedInvitJoinGroupViewHodler = null;
        ChatItemViewHolder.SendReceiveFundsViewHodler sendReceiveFundsViewHodler = null;
        /** 经费系统消息 **/
        ChatItemViewHolder.ReceivedFundsSystemViewHodler fundsSystemViewHodler = null;
        ChatItemViewHolder.ReceivedReceiveFundsViewHodler receivedReceiveFundsViewHodler = null;
        ChatItemViewHolder.ReceivedVideoViewHodler receivedVideoViewHodler = null;

        ChatItemViewHolder.SendTextViewHolder sendTextHolder = null;
        ChatItemViewHolder.SendImageViewHolder sendImageHolder = null;
        ChatItemViewHolder.SendAudioViewHolder sendAudioHolder = null;
        ChatItemViewHolder.SendLocationViewHolder sendLocationHolder = null;
        ChatItemViewHolder.SendGifViewHolder sendGifHolder = null;
        ChatItemViewHolder.SendFileViewHolder sendFileHolder = null;
        ChatItemViewHolder.SendCradViewHolder sendCradViewHolder = null;
        ChatItemViewHolder.SendRedViewHolder sendRedViewHolder = null;
        ChatItemViewHolder.SendTransferViewHolder sendTransferViewHolder = null;
        ChatItemViewHolder.SendCrownFundViewHodler sendCrownFundViewHodler = null;
        ChatItemViewHolder.SendVideoChatViewHolder sendVideoChatViewHolder = null;
        ChatItemViewHolder.SendOAViewHolder sendOAViewHolder = null;
        ChatItemViewHolder.SendOANoticeViewHolder sendOANoticeViewHolder = null;
        ChatItemViewHolder.SendOATaskViewHolder sendOATaskViewHolder = null;
        ChatItemViewHolder.SendInvitJoinGroupViewHodler sendInvitJoinGroupViewHodler = null;
        ChatItemViewHolder.SendVideoViewHolder sendVideoViewHolder = null;

        //获取消息类型
        int type = getItemViewType(position);
        if (Integer.valueOf(message.msg_content_type) == MsgContentType.ACCESS_FRIEND_VERIFY) {
            type = ChatTypeManage.TALK_RECEIVED_TEXT;
        }

        if (convertView == null) {
            convertView = ChatItemViewManager.getConvertView(type, mContext);
            switch (type) {
                case ChatTypeManage.TALK_TIME:
                    timeHolder = mChatItemViewHolder.new TimeViewHolder();
                    timeHolder.timeText = (TextView) convertView
                            .findViewById(R.id.time);
                    convertView.setTag(timeHolder);
                    break;
                case ChatTypeManage.TALK_UNREAD_MSG:
                    unreadMsgViewHolder = mChatItemViewHolder.new UnreadMsgViewHolder();
                    convertView.setTag(unreadMsgViewHolder);
                    break;
                case ChatTypeManage.TALK_SYSTEM:
                    systemHolder = mChatItemViewHolder.new SystemViewHolder();
                    convertView.setTag(systemHolder);
                    break;
                case ChatTypeManage.TALK_VERIF_MSG:
                    verifMsgViewHolder = mChatItemViewHolder.new VerifMsgViewHolder();
                    verifMsgViewHolder.verifContentText = (TextView) convertView
                            .findViewById(R.id.system_text);
                    convertView.setTag(verifMsgViewHolder);
                    break;
                case ChatTypeManage.TALK_RED_SYSTEM:
                    redSystemViewHolder = ChatItemViewManager
                            .getRedSystemViewHolder(convertView);
                    convertView.setTag(redSystemViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_NEWS:
                    newsViewHolder = ChatItemViewManager
                            .getNewsViewHolder(convertView);
                    convertView.setTag(newsViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_TEXT:
                    receivedTextHolder = ChatItemViewManager
                            .getReceivedTextViewHolder(convertView);
                    receivedTextHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedTextHolder);
                    receivedTextHolder.received_text.setOnLongClickListener(mLongClickListener);
                    receivedTextHolder.received_text.setOnTouchListener(LinkDefs.mOnTouchListener);
                    LinkDefs.extractUrl2Link(receivedTextHolder.received_text);
                    break;
                case ChatTypeManage.TALK_RECEIVED_IMAGE:
                    receivedImageHolder = ChatItemViewManager
                            .getReceivedImageViewHolder(convertView);
                    receivedImageHolder.received_image.setTag(message.content);
                    convertView.setTag(receivedImageHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_AUDIO:
                    receivedAudioHolder = ChatItemViewManager
                            .getReceivedAudioViewHolder(convertView);
                    receivedAudioHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    if (mQyxMsgView.is_loading) {
                        receivedAudioHolder.received_read_status
                                .setVisibility(View.GONE);
                        receivedAudioHolder.received_loading
                                .setVisibility(View.VISIBLE);
                    } else {
                        receivedAudioHolder.received_loading
                                .setVisibility(View.INVISIBLE);
                    }
                    convertView.setTag(receivedAudioHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_LOCATION:
                    receivedLocationHolder = ChatItemViewManager
                            .getReceivedLocationViewHolder(convertView);
                    receivedLocationHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedLocationHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_GIF:
                    receivedGifHolder = ChatItemViewManager
                            .getReceivedGifViewHolder(convertView);
                    receivedGifHolder.received_gif
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedGifHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_FILE:
                    receivedFileHolder = ChatItemViewManager
                            .getReceivedFileViewHolder(convertView);
                    receivedFileHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedFileHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_RED:
                    receivedRedViewHolder = ChatItemViewManager
                            .getReceivedRedViewHolder(convertView);
                    receivedRedViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedRedViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_TRANSFER:
                    receivedTransferViewHodler = ChatItemViewManager
                            .getGiroViewHodler(convertView, mLongClickListener);
                    break;
                case ChatTypeManage.TALK_RECEIVED_CROWNFUND:
                    receivedCrownFundViewHodler = ChatItemViewManager
                            .getReceivedCrownFundViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_CROWD_FUND_SYSTEM_INFO:
                    crowdFundSystemViewHodler = mChatItemViewHolder.new ReceivedCrowdFundSystemViewHodler();
                    crowdFundSystemViewHodler.system_tv = (TextView) convertView
                            .findViewById(R.id.system_text);
                    convertView.setTag(crowdFundSystemViewHodler);
                    break;
                case ChatTypeManage.TALK_RECEIVED_INVIT_JOIN_GROUP:
                    receivedInvitJoinGroupViewHodler = ChatItemViewManager
                            .getReceivedInvitJoinGroupViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_SEND_RECEIVE_FUNDS:
                    sendReceiveFundsViewHodler = ChatItemViewManager
                            .getSendReceiveFundsViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_FUNDS_SYSTEM_INFO:
                    fundsSystemViewHodler = mChatItemViewHolder.new ReceivedFundsSystemViewHodler();
                    fundsSystemViewHodler.system_tv = (TextView) convertView
                            .findViewById(R.id.system_text);
                    convertView.setTag(fundsSystemViewHodler);
                    break;
                case ChatTypeManage.TALK_RECEIVED_RECEIVE_FUNDS:
                    receivedReceiveFundsViewHodler = ChatItemViewManager
                            .getReceivedReceiveFundsViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_RECEIVED_CRAD:
                    receivedCradViewHolder = ChatItemViewManager
                            .getReceivedCradViewHolder(convertView);
                    receivedCradViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedCradViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_VIDEO_CHAT:
                    receivedVideoChatViewHolder = ChatItemViewManager
                            .getReceivedVideoChatViewHolder(convertView);
                    receivedVideoChatViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedVideoChatViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_VIDEO:
                    receivedVideoViewHodler = ChatItemViewManager.getReceivedVideoViewHodler(convertView);
                    receivedVideoViewHodler.group.setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedVideoViewHodler);
                    break;
                case ChatTypeManage.TALK_RECEIVED_OA:
                    receivedOAViewHolder = ChatItemViewManager
                            .getReceivedOAViewHolder(convertView);
                    receivedOAViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedOAViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_OA_NOTICE:
                    receivedOANoticeViewHolder = ChatItemViewManager
                            .getReceivedOANoticeViewHolder(convertView);
                    receivedOANoticeViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedOANoticeViewHolder);
                    break;
                case ChatTypeManage.TALK_RECEIVED_TASK:
                    receivedOATaskViewHolder = ChatItemViewManager
                            .getReceivedOATaskViewHolder(convertView);
                    receivedOATaskViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(receivedOATaskViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_TEXT:
                    sendTextHolder = ChatItemViewManager
                            .getSendTextViewHolder(convertView);
                    sendTextHolder.send_text.setTag(mQyxMsgView);
                    sendTextHolder.send_text.setOnLongClickListener(mLongClickListener);
                    sendTextHolder.send_text.setOnTouchListener(LinkDefs.mOnTouchListener);
                    convertView.setTag(sendTextHolder);
                    break;
                case ChatTypeManage.TALK_SEND_IMAGE:
                    sendImageHolder = ChatItemViewManager
                            .getSendImageViewHolder(convertView);
                    sendImageHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendImageHolder);
                    break;
                case ChatTypeManage.TALK_SEND_AUDIO:
                    sendAudioHolder = ChatItemViewManager
                            .getSendAudioViewHolder(convertView);
                    sendAudioHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendAudioHolder);
                    break;
                case ChatTypeManage.TALK_SEND_LOCATION:
                    sendLocationHolder = ChatItemViewManager
                            .getSendLocationViewHolder(convertView);
                    sendLocationHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendLocationHolder);
                    break;
                case ChatTypeManage.TALK_SEND_GIF:
                    sendGifHolder = ChatItemViewManager
                            .getSendGifViewHolder(convertView);
                    sendGifHolder.send_gif
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendGifHolder);

                    break;
                case ChatTypeManage.TALK_SEND_FILE:
                    sendFileHolder = ChatItemViewManager
                            .getSendFileViewHolder(convertView);
                    sendFileHolder.group.setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendFileHolder);
                    break;
                case ChatTypeManage.TALK_SEND_CRAD:
                    sendCradViewHolder = ChatItemViewManager
                            .getSendCradViewHolder(convertView);
                    sendCradViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendCradViewHolder);
                    break;

                case ChatTypeManage.TALK_SEND_RED:
                    sendRedViewHolder = ChatItemViewManager
                            .getSendRedViewHolder(convertView);
                    sendRedViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendRedViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_TRANSFER:
                    sendTransferViewHolder = ChatItemViewManager
                            .getSendTransferViewHolder(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_SEND_CROWNFUND:
                    sendCrownFundViewHodler = ChatItemViewManager
                            .getSendCrownFundViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_SEND_INVIT_JOIN_GROUP:
                    sendInvitJoinGroupViewHodler = ChatItemViewManager
                            .getSendInvitJoinGroupViewHodler(convertView,
                                    mLongClickListener);
                    break;
                case ChatTypeManage.TALK_SEND_VIDEO:
                    sendVideoViewHolder = ChatItemViewManager.getSendVideoViewHolder(convertView);
                    sendVideoViewHolder.group.setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendVideoViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_VIDEO_CHAT:
                    sendVideoChatViewHolder = ChatItemViewManager
                            .getSendVideoChatViewHolder(convertView);
                    sendVideoChatViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendVideoChatViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_OA:
                    sendOAViewHolder = ChatItemViewManager
                            .getSendOAViewHolder(convertView);
                    sendOAViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendOAViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_OA_NOTICE:
                    sendOANoticeViewHolder = ChatItemViewManager
                            .getSendOANoticeViewHolder(convertView);
                    sendOANoticeViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendOANoticeViewHolder);
                    break;
                case ChatTypeManage.TALK_SEND_TASK:
                    sendOATaskViewHolder = ChatItemViewManager
                            .getSendOATaskViewHolder(convertView);
                    sendOATaskViewHolder.group
                            .setOnLongClickListener(mLongClickListener);
                    convertView.setTag(sendOATaskViewHolder);
                    break;
            }

        } else {
            switch (type) {
                case ChatTypeManage.TALK_TIME:
                    timeHolder = (ChatItemViewHolder.TimeViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_UNREAD_MSG:
                    unreadMsgViewHolder = (ChatItemViewHolder.UnreadMsgViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SYSTEM:
                    systemHolder = (ChatItemViewHolder.SystemViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_VERIF_MSG:
                    verifMsgViewHolder = (ChatItemViewHolder.VerifMsgViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_RED_SYSTEM:
                    redSystemViewHolder = (ChatItemViewHolder.RedSystemViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_NEWS:
                    newsViewHolder = (ChatItemViewHolder.NewsViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_TEXT:
                    receivedTextHolder = (ChatItemViewHolder.ReceivedTextViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_IMAGE:
                    receivedImageHolder = (ChatItemViewHolder.ReceivedImageViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_AUDIO:
                    receivedAudioHolder = (ChatItemViewHolder.ReceivedAudioViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_LOCATION:
                    receivedLocationHolder = (ChatItemViewHolder.ReceivedLocationViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_GIF:
                    receivedGifHolder = (ChatItemViewHolder.ReceivedGifViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_FILE:
                    receivedFileHolder = (ChatItemViewHolder.ReceivedFileViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_CRAD:
                    receivedCradViewHolder = (ChatItemViewHolder.ReceivedCradViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_RED:
                    receivedRedViewHolder = (ChatItemViewHolder.ReceivedRedViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_TRANSFER:
                    receivedTransferViewHodler = (ChatItemViewHolder.ReceivedTransferViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_CROWNFUND:
                    receivedCrownFundViewHodler = (ChatItemViewHolder.ReceivedCrownFundViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_CROWD_FUND_SYSTEM_INFO:
                    crowdFundSystemViewHodler = (ChatItemViewHolder.ReceivedCrowdFundSystemViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_INVIT_JOIN_GROUP:
                    receivedInvitJoinGroupViewHodler = (ChatItemViewHolder.ReceivedInvitJoinGroupViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_RECEIVE_FUNDS:
                    sendReceiveFundsViewHodler = (ChatItemViewHolder.SendReceiveFundsViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_FUNDS_SYSTEM_INFO:
                    fundsSystemViewHodler = (ChatItemViewHolder.ReceivedFundsSystemViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_RECEIVE_FUNDS:
                    receivedReceiveFundsViewHodler = (ChatItemViewHolder.ReceivedReceiveFundsViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_VIDEO_CHAT:
                    receivedVideoChatViewHolder = (ChatItemViewHolder.ReceivedVideoChatViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_VIDEO:
                    receivedVideoViewHodler = (ChatItemViewHolder.ReceivedVideoViewHodler) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_OA:
                    receivedOAViewHolder = (ChatItemViewHolder.ReceivedOAViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_OA_NOTICE:
                    receivedOANoticeViewHolder = (ChatItemViewHolder.ReceivedOANoticeViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_RECEIVED_TASK:
                    receivedOATaskViewHolder = (ChatItemViewHolder.ReceivedOATaskViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_TEXT:
                    sendTextHolder = (ChatItemViewHolder.SendTextViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_IMAGE:
                    sendImageHolder = (ChatItemViewHolder.SendImageViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_AUDIO:
                    sendAudioHolder = (ChatItemViewHolder.SendAudioViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_LOCATION:
                    sendLocationHolder = (ChatItemViewHolder.SendLocationViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_GIF:
                    sendGifHolder = (ChatItemViewHolder.SendGifViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_FILE:
                    sendFileHolder = (ChatItemViewHolder.SendFileViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_CRAD:
                    sendCradViewHolder = (ChatItemViewHolder.SendCradViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_RED:
                    sendRedViewHolder = (ChatItemViewHolder.SendRedViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_TRANSFER:
                    sendTransferViewHolder = (ChatItemViewHolder.SendTransferViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_INVIT_JOIN_GROUP:
                    sendInvitJoinGroupViewHodler = (ChatItemViewHolder.SendInvitJoinGroupViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_CROWNFUND:
                    sendCrownFundViewHodler = (ChatItemViewHolder.SendCrownFundViewHodler) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_VIDEO_CHAT:
                    sendVideoChatViewHolder = (ChatItemViewHolder.SendVideoChatViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_VIDEO:
                    sendVideoViewHolder = (ChatItemViewHolder.SendVideoViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_OA:
                    sendOAViewHolder = (ChatItemViewHolder.SendOAViewHolder) convertView.getTag();
                    break;
                case ChatTypeManage.TALK_SEND_OA_NOTICE:
                    sendOANoticeViewHolder = (ChatItemViewHolder.SendOANoticeViewHolder) convertView
                            .getTag();
                    break;
                case ChatTypeManage.TALK_SEND_TASK:
                    sendOATaskViewHolder = (ChatItemViewHolder.SendOATaskViewHolder) convertView
                            .getTag();
                    break;
            }
        }

        baseHolder = (ChatItemViewHolder.BaseViewHolder) convertView.getTag();
        if (baseHolder.timeText != null
                && message.msg_content_type == MsgOtherType.msgTime) {
            baseHolder.timeText.setText(QyxDateUtils
                    .generateDateTimeString(new Date(message.msg_time * 1000)));
        }

        if (baseHolder.send_status != null) {
            baseHolder.send_status.setTag(position);
            if (message.send_status.equals("")) {
                baseHolder.send_loading.setVisibility(View.VISIBLE);
            } else {
                baseHolder.send_loading.setVisibility(View.INVISIBLE);
            }
        }

        if (baseHolder.avatar != null) {
            baseHolder.avatar.SetUrl(avatar_path);
        }

        if (message.sessionModel.getSessionType() == PacketType.GROUP) {
            if (baseHolder.received_name != null) {
                if (is_show_group_member_name == 1) {
                    /** 显示群成员昵称是：优先显示登录用户备注名 **/
                    String from_cust_name = message.from_cust_name;
                    String temp = IMApplication.config
                            .getFriendsRemarkName(message.from_cust_id + "");
                    if (!TextUtils.isEmpty(temp)) {
                        from_cust_name = temp;
                    }
                    baseHolder.received_name.setText(from_cust_name);
                    baseHolder.received_name.setVisibility(View.VISIBLE);
                } else {
                    baseHolder.received_name.setVisibility(View.GONE);
                }
            }
        } else {
            if (baseHolder.received_name != null)
                baseHolder.received_name.setVisibility(View.GONE);
        }

        if (baseHolder.avatar != null) {
            baseHolder.avatar.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ActivityHandle.startUserDetailActivity((Activity) mContext,
                            message.from_cust_id + "");
                }
            });
            baseHolder.avatar
                    .setOnLongClickListener(new View.OnLongClickListener() {

                        @Override
                        public boolean onLongClick(View v) {
                            if (!(message.from_cust_id + "")
                                    .equals(IMApplication.getCustId())) {
                                String name = message.from_cust_name;
                                Intent intent = new Intent();
                                intent.putExtra("cust_name", name);
                                intent.setAction(BroadcastAction.ACTION_MESSAGE_AT);
                                mContext.sendBroadcast(intent);
                            }
                            return true;
                        }
                    });
        }
        if (baseHolder.group != null) {
            baseHolder.group.setTag(mQyxMsgView);
            baseHolder.group.setOnLongClickListener(mLongClickListener);
            baseHolder.group.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ChatItemDataManager.onGroupOnClick(mContext, message,
                            mChatMsgManage, _msgList);
                }
            });
        }

        if (baseHolder.send_loading != null) {
            baseHolder.send_loading.setVisibility(View.INVISIBLE);
        }

        if (baseHolder.send_status != null) {
            if (message.send_status.equals("n")) {
                baseHolder.send_status.setVisibility(View.VISIBLE);

            } else {
                baseHolder.send_status.setVisibility(View.GONE);
                if (message.send_status.equals("")) {
                    baseHolder.send_loading.setVisibility(View.VISIBLE);
                }
            }
            baseHolder.send_status.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    showRetransSendMsgDialog(v);
                }
            });
        }
        switch (type) {
            case ChatTypeManage.TALK_SYSTEM:
                systemHolder.systemText = (TextView) convertView
                        .findViewById(R.id.system_text);
                // TODO 设置系统消息内容
                ChatItemDataManager.setSystemTv(systemHolder.systemText,
                        message.content_json, message.content);
                break;
            case ChatTypeManage.TALK_VERIF_MSG:
                verifMsgViewHolder.verifContentText.setText(message.content);
                // TODO 渲染
                int color = Color.argb(255, 2, 150, 209);
                SpannableStringBuilder builder = new SpannableStringBuilder(
                        verifMsgViewHolder.verifContentText.getText().toString());
                ClickableSpan cs = new MyClickableSpan(message.to_cust_id + "");
                builder.setSpan(cs, message.content.length() - 6,
                        message.content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ForegroundColorSpan normalSpan = new ForegroundColorSpan(color);
                builder.setSpan(normalSpan, message.content.length() - 6,
                        message.content.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                verifMsgViewHolder.verifContentText.setText(builder);
                verifMsgViewHolder.verifContentText
                        .setMovementMethod(LinkMovementMethod.getInstance());
                break;
            case ChatTypeManage.TALK_RED_SYSTEM:
                ChatItemDataManager.setSystemTv(redSystemViewHolder.redContentText,
                        message.content_json, message.content);
                break;
            case ChatTypeManage.TALK_RECEIVED_NEWS:
                // 设置新闻布局信息
                ChatItemDataManager.showNewsMsg(mLongClickListener, mQyxMsgView,
                        mContext, newsViewHolder.news_content_layout);
                break;
            case ChatTypeManage.TALK_RECEIVED_TEXT:
                String receivedAtTop = "";
                if (message.msg_content_type == MsgContentType.ALTER_GROUP_TALK_INTRO) {
                    receivedAtTop = "@" + mContext.getString(R.string.at_all)
                            + "\n";
                }
                receivedTextHolder.received_text.setText(mEmoji.getSpannedRate(
                        receivedAtTop + message.content, mContext, 2));
                break;
            case ChatTypeManage.TALK_RECEIVED_IMAGE:
                ChatItemDataManager.setReceivedImageData(mContext,
                        receivedImageHolder, message);
                break;
            case ChatTypeManage.TALK_RECEIVED_AUDIO:
                ChatItemDataManager.setReceivedAudioData(mQyxMsgView, message,
                        receivedAudioHolder);
                MsgAudioModel receivedAudioModel = (MsgAudioModel) message.baseContentModel;
                if (receivedAudioModel != null) {
                    receivedAudioHolder.group
                            .setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                                    mChatMsgManage.getSoundBgWidth(
                                            receivedAudioModel.getSecond(),
                                            sound_msg_bg_total_width),
                                    LayoutParams.WRAP_CONTENT));
                }
                receivedAudioHolder.group.setOnClickListener(mAudioClickListener);

                break;
            case ChatTypeManage.TALK_RECEIVED_LOCATION:
                receivedLocationHolder.received_location
                        .setAddress(message.content);
                break;
            case ChatTypeManage.TALK_RECEIVED_GIF:
                receivedGifHolder.received_gif.setTag(mQyxMsgView);
                MsgGifModel receivedMsgGifModel = (MsgGifModel) message.baseContentModel;
                if (receivedMsgGifModel != null)
                    ChatItemDataManager.showGifImage(mContext,
                            receivedGifHolder.received_gif, message);
                break;
            case ChatTypeManage.TALK_RECEIVED_FILE:
                ChatItemDataManager.setReceivedFileData(mContext, message,
                        mSendFile, receivedFileHolder);
                break;
            case ChatTypeManage.TALK_RECEIVED_CRAD:
                ChatItemDataManager.setReceivedCradData(mContext, message,
                        receivedCradViewHolder);
                break;
            case ChatTypeManage.TALK_RECEIVED_RED:
                receivedRedViewHolder.received_money_content_tv
                        .setText(message.content);
                break;
            case ChatTypeManage.TALK_RECEIVED_TRANSFER:
                ChatItemDataManager.setRecivedTransferData(message,
                        receivedTransferViewHodler);
                break;
            case ChatTypeManage.TALK_RECEIVED_CROWNFUND:
                ChatItemDataManager.setReceivedCrownFundData(mContext, message,
                        receivedCrownFundViewHodler);
                break;
            case ChatTypeManage.TALK_CROWD_FUND_SYSTEM_INFO:
                ChatItemDataManager.setCrowFundSystemData(mContext, message,
                        crowdFundSystemViewHodler);
                break;
            case ChatTypeManage.TALK_RECEIVED_INVIT_JOIN_GROUP:
                ChatItemDataManager.setReceivedInvitJoinGroupData(mContext,
                        message, receivedInvitJoinGroupViewHodler);
                break;
            case ChatTypeManage.TALK_SEND_RECEIVE_FUNDS:
                ChatItemDataManager.setSendReceiveFundsData(mContext, message,
                        sendReceiveFundsViewHodler);
                break;
            case ChatTypeManage.TALK_FUNDS_SYSTEM_INFO:
                ChatItemDataManager.setReceivedFundsSystemInfo(mContext, message,
                        fundsSystemViewHodler);
                break;
            case ChatTypeManage.TALK_RECEIVED_RECEIVE_FUNDS:
                ChatItemDataManager.setReceivedReceiveFundsData(mContext, message,
                        receivedReceiveFundsViewHodler);
                break;
            case ChatTypeManage.TALK_RECEIVED_VIDEO_CHAT:
                ChatItemDataManager.setReceivedVideoChatData(message,
                        receivedVideoChatViewHolder);
                break;
            case ChatTypeManage.TALK_RECEIVED_VIDEO:
                ChatItemDataManager.setReceivedVideoData(mContext, message, receivedVideoViewHodler);
                break;
            case ChatTypeManage.TALK_RECEIVED_OA:
                ChatItemDataManager
                        .setReceivedOAData(message, receivedOAViewHolder);
                break;
            case ChatTypeManage.TALK_RECEIVED_OA_NOTICE:
                ChatItemDataManager.setReceivedOANoticeData(message,
                        receivedOANoticeViewHolder);
                break;
            case ChatTypeManage.TALK_RECEIVED_TASK:
                ChatItemDataManager.setReceivedOaTaskData(mContext, message,
                        receivedOATaskViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_TEXT:
                String sendAtTop = "";
                if (message.msg_content_type == MsgContentType.ALTER_GROUP_TALK_INTRO) {
                    sendAtTop = "@" + mContext.getString(R.string.at_all) + "\n";
                }
                sendTextHolder.send_text.setText(mEmoji.getSpannedRate(sendAtTop
                        + message.content, mContext, 2));
                sendTextHolder.send_text.setOnLongClickListener(mLongClickListener);
                LinkDefs.extractUrl2Link(sendTextHolder.send_text);
                break;
            case ChatTypeManage.TALK_SEND_IMAGE:
                ChatItemDataManager.setSendImageData(mContext, mQyxMsgView,
                        message, sendImageHolder);
                break;

            case ChatTypeManage.TALK_SEND_AUDIO:
                ChatItemDataManager.setSendAudio(mQyxMsgView, message,
                        sendAudioHolder);
                MsgAudioModel sendAudioModel = (MsgAudioModel) message.baseContentModel;
                if (sendAudioModel != null) {
                    sendAudioHolder.group
                            .setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                                    mChatMsgManage.getSoundBgWidth(
                                            sendAudioModel.getSecond(),
                                            sound_msg_bg_total_width),
                                    LayoutParams.WRAP_CONTENT));
                }

                sendAudioHolder.group.setOnClickListener(mAudioClickListener);
                break;
            case ChatTypeManage.TALK_SEND_LOCATION:
                sendLocationHolder.send_Location.setAddress(message.content);
                break;
            case ChatTypeManage.TALK_SEND_GIF:
                sendGifHolder.send_status.setTag(position);
                sendGifHolder.send_gif.setTag(mQyxMsgView);
                MsgGifModel sendMsgGifModel = (MsgGifModel) message.baseContentModel;
                if (sendMsgGifModel != null)
                    ChatItemDataManager.showGifImage(mContext,
                            sendGifHolder.send_gif, message);
                break;
            case ChatTypeManage.TALK_SEND_FILE:
                ChatItemDataManager.setSendFileData(mContext, message, mSendFile,
                        sendFileHolder);
                break;
            case ChatTypeManage.TALK_SEND_CRAD:
                ChatItemDataManager.setSendCradData(mContext, message,
                        sendCradViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_RED:
                sendRedViewHolder.send_money_content_tv.setText(message.content);
                break;
            case ChatTypeManage.TALK_SEND_TRANSFER:
                ChatItemDataManager.setSendTransferData(message,
                        sendTransferViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_INVIT_JOIN_GROUP:
                ChatItemDataManager.setSendInvitJoinGroupData(message,
                        sendInvitJoinGroupViewHodler);
                break;
            case ChatTypeManage.TALK_SEND_CROWNFUND:
                ChatItemDataManager.setSendCrownFundData(mContext, message,
                        sendCrownFundViewHodler);
                break;
            case ChatTypeManage.TALK_SEND_VIDEO_CHAT:
                ChatItemDataManager.setSendVideoData(message,
                        sendVideoChatViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_VIDEO:
                ChatItemDataManager.sendVideoData(mContext, message,
                        sendVideoViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_OA:
                ChatItemDataManager.setSendOAData(message, sendOAViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_OA_NOTICE:
                ChatItemDataManager.setSendOANoticeData(message,
                        sendOANoticeViewHolder);
                break;
            case ChatTypeManage.TALK_SEND_TASK:
                ChatItemDataManager.setSendOATaskData(mContext, message,
                        sendOATaskViewHolder);
                break;
        }

        convertView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Utils.hideSoftKeyboard(mEditText);
                return false;
            }
        });

        return convertView;

    }

    @Override
    public int getItemViewType(int position) {
        return ChatTypeManage.getItemViewType(_msgList.get(position).msg);
    }

    OnClickListener mAudioClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            QyxMsgView qyxMsgView = (QyxMsgView) v.getTag();
            addPlayMedia(qyxMsgView);
            downloadMediaAndPlay(qyxMsgView);
        }
    };

    /**
     * View 长按事件
     */
    View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (mEditText != null) {
                Utils.hideSoftKeyboard(mEditText);
            }
            return mChatMsgManage.viewLongClick(v, new ChatMsgManage.IDeleteOrWithdrawMsg() {

                @Override
                public void onDeleteMsg(QyxMsg qyxMsg) {
                    delMsg(qyxMsg);
                }

                @Override
                public void onWithdrawMsg(QyxMsg qyxMsg) {
                    // 撤销消息
                    if (qyxMsg.sessionModel.getSessionType() == PacketType.PERSONAL) {
                        revokeMsg("", qyxMsg.sessionModel.getSessionId() + "",
                                qyxMsg);
                    } else {
                        revokeMsg(qyxMsg.sessionModel.getSessionId() + "", "",
                                qyxMsg);
                    }
                }
            });
        }
    };

    /**
     * 删除消息记录
     *
     * @param msg
     */
    private void delMsg(QyxMsg msg) {
        int len = _msgList.size();
        int del_index = 0;
        for (int i = 0; i < len; i++) {
            if (_msgList.get(i).msg.msg_no.equals(msg.msg_no)) {
                takeMsgManager.deleteMsg(msg);
                mChatMsgManage.updateTopMsg(msg);
                _msgList.remove(i);
                del_index = i;
                break;
            }
        }

        if (del_index > 0
                && _msgList.get(del_index - 1).msg.msg_content_type == MsgOtherType.msgTime
                && (del_index == _msgList.size() || (del_index < _msgList
                .size() && _msgList.get(del_index).msg.msg_content_type == MsgOtherType.msgTime))) {
            _msgList.remove(del_index - 1);
            time_msg_count--;
            notifyDataSetChanged();
        } else {
            notifyDataSetChanged();
        }
    }

    public void addMessage(QyxMsgView message) {
        if (_msgList.isEmpty()
                || message.msg.msg_time
                - _msgList.get(_msgList.size() - 1).msg.msg_time >= 60 * 5) {
            QyxMsgView mQyxMsgViewTime = new QyxMsgView();
            QyxMsg qyxMsgTime = new QyxMsg();
            qyxMsgTime.msg_content_type = MsgOtherType.msgTime;
            qyxMsgTime.msg_time = message.msg.msg_time;
            mQyxMsgViewTime.is_playing = false;
            mQyxMsgViewTime.is_loading = false;
            mQyxMsgViewTime.msg = qyxMsgTime;
            _msgList.add(mQyxMsgViewTime);
            time_msg_count++;
        }

        _msgList.add(message);
        notifyDataSetChanged();
    }

    /***
     * 添加未读消息提示线
     */
    public void addUnreadMsgLineToTop() {
        unread_msg_line = 1;
        QyxMsgView msgView = new QyxMsgView();
        QyxMsg qyxMsg = new QyxMsg();
        qyxMsg.msg_content_type = MsgOtherType.msgPromptNewMsg;
        msgView.msg = qyxMsg;
        _msgList.add(0, msgView);
        notifyDataSetChanged();
    }

    public void prependMessage(ArrayList<QyxMsgView> messages) {
        _msgList.addAll(0, messages);
        notifyDataSetChanged();
    }

    public void appendMessage(ArrayList<QyxMsgView> messages) {
        _msgList.addAll(getCount(), messages);
        notifyDataSetChanged();
    }

    public QyxMsgView last_palying_index;
    View ListItemView;

    public void stopPlayRecord() {
        if (Player.getInstance().GetIsPlaying()) {
            Player.getInstance().Stop();

            if (last_palying_index != null) {
                last_palying_index.is_playing = false;
                notifyDataSetChanged();
            }
        }
    }

    /**
     * 播放语音
     *
     * @param qyxMsgView
     * @throws IllegalArgumentException
     * @throws SecurityException
     * @throws IllegalStateException
     * @throws IOException
     */
    public void playRecord(final QyxMsgView qyxMsgView) {

        if (Player.getInstance().GetIsPlaying()) {
            Player.getInstance().Stop();

            if (last_palying_index != null && last_palying_index == qyxMsgView) {
                last_palying_index.is_playing = false;
                notifyDataSetChanged();
                return;
            }
        }

        if (last_palying_index != null) {
            last_palying_index.is_playing = false;
        }

        if (qyxMsgView == null) {
            notifyDataSetChanged();
            return;
        }
        Player.getInstance().Play(
                qyxMsgView.msg.baseContentModel.getAttachmentModel()
                        .getFileLocalPath());
        last_palying_index = qyxMsgView;
        last_palying_index.is_playing = true;
        notifyDataSetChanged();
    }

    /***
     * 下载文件附件
     *
     * @param qyxMsgView
     */
    private void downloadMsg(final QyxMsgView qyxMsgView) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "";
                if (qyxMsgView.msg.msg_content_type == MsgContentType.AUDIO) {

                    MsgAudioModel msgAudioModel = (MsgAudioModel) qyxMsgView.msg.baseContentModel;
                    AttachModel attachModel = null;
                    if (msgAudioModel != null) {
                        attachModel = (AttachModel) msgAudioModel
                                .getAttachmentModel();
                    }

                    String url = APIConfiguration.getFileDownloadPath(
                            attachModel.getFileId(), attachModel.getFileHash());
                    path = fileUtils.downloadFile(url, "amr",
                            DateUtils.getCurrentMills() + ".amr", null);
                }
                if (!TextUtils.isEmpty(path)) {
                    qyxMsgView.msg.baseContentModel.getAttachmentModel()
                            .setFileLocalPath(path);
                }

                Message msg = myHandler.obtainMessage();
                msg.arg1 = qyxMsgView.index;

                if (!TextUtils.isEmpty(path)) {
                    takeMsgManager.updateMsgFilePath(qyxMsgView.msg._id, path);
                    msg.what = 0;
                } else {
                    msg.what = 1;
                }

                myHandler.sendMessage(msg);
            }
        }).start();
    }

    private void updateListView(int position, boolean down_status) {
        _msgList.get(position).is_loading = false;
        if (down_status) {
            if (_msgList.get(position).msg.have_read != 1) {
                takeMsgManager.updateMsgHaveRead(
                        _msgList.get(position).msg._id, "1");
            }
            _msgList.get(position).msg.have_read = 1;
            _msgList.get(position).is_playing = true;
            playRecord(_msgList.get(position));
        }
        notifyDataSetChanged();
    }

    /**
     * 修改消息发送状态
     *
     * @param msg_no
     * @param status
     */
    public void updateListViewSendStatus(String msg_no, String status) {
        int len = _msgList.size();
        for (int j = 0; j < len; j++) {
            if (msg_no.equals(_msgList.get(j).msg.msg_no)
                    && _msgList.get(j).msg.msg_content_type != MsgOtherType.msgTime) {
                _msgList.get(j).msg.send_status = status;
                notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 修改视频通话结果类型
     *
     * @param msg_no                 消息编号
     * @param video_chat_result_type 结果类型 VideoChatResultType
     */
    public void updateListViewVideChatResultType(String msg_no,
                                                 final int video_chat_result_type) {
        int len = _msgList.size();
        for (int j = 0; j < len; j++) {
            if (msg_no.equals(_msgList.get(j).msg.msg_no)
                    && _msgList.get(j).msg.msg_content_type != MsgOtherType.msgTime) {
                if (_msgList.get(j).msg.msg_content_type == MsgContentType.REQUEST_VIDEO_CHAT) {
                    MsgRequestVideoChatModel chatModel = (MsgRequestVideoChatModel) _msgList
                            .get(j).msg.baseContentModel;
                    if (chatModel != null) {
                        chatModel
                                .setVideoChatResultType(video_chat_result_type);
                    }
                }
                notifyDataSetChanged();
                break;
            }
        }
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            final int position = msg.arg1;
            if (msg.what == 0) {
                updateListView(position, true);
            } else if (msg.what == 1) {
                updateListView(position, false);
            }

            return false;
        }
    });


    /**
     * 对方撤销某条消息
     *
     * @param msg_no
     */
    public void otherWithdrawMsg(String msg_no) {
        for (int i = 0, size = _msgList.size(); i < size; i++) {
            if (_msgList.get(i).msg.msg_no.equals(msg_no)) {
                QyxMsg qyxMsg = _msgList.get(i).msg;
                _msgList.remove(i);
                updateOtherWithdrawMsg(qyxMsg);
                notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 修改对方发来的撤销消息
     *
     * @param message
     */
    private void updateOtherWithdrawMsg(QyxMsg message) {
        QyxMsg qyxMsg = new QyxMsg();
        qyxMsg.msg_content_type = 0;
        qyxMsg.content = MessageFormat.format(
                mContext.getString(R.string.withdraw_one_msg),
                message.from_cust_name);
        qyxMsg.to_cust_id = message.to_cust_id;
        qyxMsg.from_cust_id = message.from_cust_id;
        qyxMsg.sessionModel.setSessionId(message.sessionModel.getSessionId());
        qyxMsg.sessionModel.setSessionType(message.sessionModel
                .getSessionType());
        qyxMsg.msg_no = qyxMsg
                .getMsgNo(qyxMsg.from_cust_id + "", qyxMsg.to_cust_id + "",
                        qyxMsg.sessionModel.getSessionId() + "");
        QyxMsgView msgView = new QyxMsgView();
        msgView.msg = qyxMsg;
        _msgList.add(msgView);
    }

    /**
     * 撤销消息成功，修改本地消息的状态
     *
     * @param message
     * @return
     */
    private void updateLocaWithdrawMsg(QyxMsg message) {
        mContext.sendBroadcast(new Intent(
                BroadcastAction.ACTION_CLOSE_DIALOG_LOADING_ACTIVITY));
        QyxMsg qyxMsg = new QyxMsg();
        qyxMsg.msg_content_type = 0;
        qyxMsg.content = mContext.getResources()
                .getString(R.string.me_withdraw);
        qyxMsg.to_cust_id = message.to_cust_id;
        qyxMsg.from_cust_id = message.from_cust_id;
        qyxMsg.sessionModel = message.sessionModel;
        qyxMsg.msg_no = qyxMsg
                .getMsgNo(qyxMsg.from_cust_id + "", qyxMsg.to_cust_id + "",
                        qyxMsg.sessionModel.getSessionId() + "");
        takeMsgManager.insertMsg(qyxMsg);

        QyxMsgView msgView = new QyxMsgView();
        msgView.msg = qyxMsg;
        _msgList.add(msgView);
        notifyDataSetChanged();
        TopListMsgManager topListMsgManager = new TopListMsgManager();
        topListMsgManager.updateTopMsgByField(
                message.sessionModel.getSessionId(),
                message.sessionModel.getSessionType(), DBTopMsgColumns.CONTENT,
                mContext.getResources().getString(R.string.me_withdraw));
        IMApplication.IS_REFRESH_TOP_MSG = true;
    }

    private void downloadMediaAndPlay(QyxMsgView qyxMsgView) {
        String localFilePath = qyxMsgView.msg.baseContentModel
                .getAttachmentModel().getFileLocalPath();
        if (TextUtils.isEmpty(localFilePath)) {
            downloadMsg(qyxMsgView);
            qyxMsgView.is_loading = true;
            notifyDataSetChanged();
        } else {
            if (qyxMsgView.msg.have_read != 1) {
                takeMsgManager.updateMsgHaveRead(qyxMsgView.msg._id, "1");
            }

            File file = new File(localFilePath);
            if (!file.exists()) {
                downloadMsg(qyxMsgView);
            } else {
                qyxMsgView.msg.have_read = 1;
                qyxMsgView.is_playing = true;
                playRecord(qyxMsgView);
            }
        }
    }

    private void addPlayMedia(QyxMsgView qyxMsgView) {
        playMediaList = new ArrayList();
        if (_msgList != null) {
            for (int i = 0, size = _msgList.size(); i < size; i++) {
                if (_msgList.get(i).msg.msg_content_type == MsgContentType.AUDIO
                        && _msgList.get(i).msg.from_cust_id != Long
                        .valueOf(IMApplication.getCustId())) {
                    if (qyxMsgView.msg.msg_time < _msgList.get(i).msg.msg_time
                            && _msgList.get(i).msg.have_read == 0) {
                        playMediaList.add(_msgList.get(i));
                    }
                }
            }
        }
    }

    /**
     * 播放列表中的语音
     */
    private void playMediaByTempList() {
        for (int i = 0, size = playMediaList.size(); i < size; i++) {
            if (playMediaList.get(i).msg.have_read == 0) {
                for (int j = 0, length = _msgList.size(); j < length; j++) {
                    if (_msgList.get(j).msg.msg_no
                            .equals(playMediaList.get(i).msg.msg_no)) {
                        if (_msgList.get(j).msg.have_read != 1) {
                            takeMsgManager.updateMsgHaveRead(
                                    _msgList.get(j).msg._id, "1");
                        }
                        downloadMediaAndPlay(_msgList.get(j));
                        playMediaList.get(i).msg.have_read = 1;
                        break;
                    }
                }
                break;
            }
        }
    }

    /**
     * 撤销消息
     *
     * @param chat_id
     * @param cust_id
     * @param qyxMsg
     */
    private void revokeMsg(String chat_id, String cust_id, final QyxMsg qyxMsg) {
        RevokeMsgInvokeItem item = new RevokeMsgInvokeItem(chat_id, cust_id,
                qyxMsg.msg_no);
        HttpRequestHandle.onBaseRequest(item, HttpRequestType.SERVER_ONLY,
                new HttpRequestHandle.IRequestResultListener() {

                    @Override
                    public void onResult(Object resultObject, boolean isCache,
                                         String failReason) {
                        if (resultObject != null) {
                            RevokeMsgInvokeItem.RevokeMsgInvokeItemResult result = ((RevokeMsgInvokeItem) resultObject)
                                    .getOutPut();
                            if (result != null) {
                                if (result.status == HttpInvokeResultCode.RESULT_OK) {
                                    // TODO
                                    takeMsgManager
                                            .deleteMsgByMsgNo(qyxMsg.msg_no);
                                    deleteData(qyxMsg.msg_no);
                                    updateLocaWithdrawMsg(qyxMsg);
                                } else if (!TextUtils.isEmpty(result.msg)) {
                                    IMApplication.showToast(result.msg);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 删除列表中某条数据
     *
     * @param msg_no
     */
    private void deleteData(String msg_no) {
        for (int i = 0, size = _msgList.size(); i < size; i++) {
            if (_msgList.get(i).msg.msg_no.equals(msg_no)) {
                _msgList.remove(i);
                notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 修改某条消息为发送失败
     *
     * @param msg_no
     */
    public void updateMsgFailed(String msg_no) {
        for (int i = 0, size = _msgList.size(); i < size; i++) {
            if (_msgList.get(i).msg.msg_no.equals(msg_no)) {
                _msgList.get(i).msg.send_status = "n";
                notifyDataSetChanged();
                break;
            }

        }
    }

    /**
     * 渲染并点击
     *
     * @author SL
     */
    class MyClickableSpan extends ClickableSpan {

        public MyClickableSpan() {
        }

        public String cust_id;

        public MyClickableSpan(String _cust_id) {
            this.cust_id = _cust_id;
        }

        @Override
        public void onClick(View widget) {
            sendVerifDialog(cust_id);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    }

    private void sendVerifDialog(final String cust_id) {
        DialogUtility.showEditDialog(mContext, true, new DialogUtility.IEditDialogListener() {

            @Override
            public void onClick(String editContent) {
                applyAddFriend(cust_id, editContent);
            }
        });
    }

    /**
     * 申请加好友
     */
    private void applyAddFriend(String cust_id, String notes) {
        final ZProgressHUD progressHUD = new ZProgressHUD(mContext);
        progressHUD.show();
        ContactsHandle.applyAddFriend(cust_id, notes, new OnCommonCallBack() {

            @Override
            public void onSuccess(Object result) {
                progressHUD.dismiss();
                ApplyAddFriendInvokItem.ApplyAddFriendInvokItemResult results = (ApplyAddFriendInvokItem.ApplyAddFriendInvokItemResult) result;
                if (!TextUtils.isEmpty(results.msg))
                    IMApplication.showToast(results.msg);
                if (results != null
                        && results.status == HttpInvokeResultCode.RESULT_OK) {
                }
            }

            @Override
            public void onFailed(String reason) {
                progressHUD.dismiss();
                if (!TextUtils.isEmpty(reason))
                    IMApplication.showToast(reason);
            }
        });

    }

    /**
     * 提示是否重复消息
     *
     * @param v
     */
    private void showRetransSendMsgDialog(final View v) {
        DialogUtility.showDialog(mContext, R.string.retrans_send_msg,
                R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        retransSendMsg(v);
                    }
                });
    }

    private void retransSendMsg(View v) {

        final int index = (Integer) v.getTag();
        _msgList.get(index).is_loading = true;
        _msgList.get(index).msg.send_status = "";
        takeMsgManager.deleteMsgByMsgNo(_msgList.get(index).msg.msg_no);

        BaseContentModel baseContentModel = _msgList.get(index).msg.baseContentModel;
        SendMsgHandle.sendMsg(baseContentModel,
                _msgList.get(index).msg.sessionModel, new SendMsgHandle.ISendMsgCallBack() {

                    @Override
                    public void onSendMsgResult(int sendMsgResult, QyxMsg qyxMsg) {
                        if (sendMsgResult != SendMsgCallBackResult.SUCCESS_RESULT
                                && qyxMsg.send_status.equals("n")) {
                            // TODO 非好友
                            for (int i = 0, size = _msgList.size(); i < size; i++) {
                                if (_msgList.get(i).msg.msg_no
                                        .equals(qyxMsg.msg_no)) {
                                    _msgList.get(i).msg.send_status = "n";
                                    break;
                                }
                            }
                        } else {
                            QyxMsgView msgView = new QyxMsgView();
                            msgView.msg = qyxMsg;
                            _msgList.add(msgView);
                        }
                        notifyDataSetChanged();
                    }
                }, new SendMsgHandle.IUploadAttachFaild() {

                    @Override
                    public void onUploadFailed(String msg_no) {
                        if (!TextUtils.isEmpty(msg_no)) {
                            updateMsgFailed(msg_no);
                        }
                    }
                });
        _msgList.remove(index);
        notifyDataSetChanged();

    }


}
